#import <Foundation/Foundation.h>
#import "FetchTrain.h"

void fetch_train_stops(NSString *trainCode, NSString *dt){
	
	NSArray *stops = [FetchTrain code:trainCode dateAt:dt];
	
	if(stops != nil){
		NSLog(@"%s", stops);
		NSMutableString *csv = [NSMutableString stringWithCapacity:50];
		int i;
		for(i=0;i<[stops count]; i++){
			NSArray *stop = [stops objectAtIndex:i];
			
			int j;
			BOOL firstCol = YES;
			for(j=0; j<[stop count]; j++){
				NSString *delimiter = firstCol ? @"" : @",";
				[csv appendFormat:@"%@%@", delimiter, [stop objectAtIndex:j]];
				firstCol = NO;
			}
			[csv appendFormat:@"\n"];
		}
		
		NSLog(@"%@", csv);
		
		
		NSArray *docPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *csvPath = [NSString stringWithFormat:@"%@/12306/%@.csv", [docPath objectAtIndex:0], trainCode];
		NSLog(@"%@", csvPath);
		[csv writeToFile:csvPath atomically:YES encoding:NSUTF8StringEncoding error:nil];

		
	} else {
		NSLog(@"no train: %@", trainCode);
	}
	
}

int main (int argc, const char * argv[]) {
	
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
	

	
	int number;

	NSArray *typeCode = [NSArray arrayWithObjects:@"T", @"", @"K", @"Z", @"C", @"G", @"D", @"N", nil];

	NSArray *dateCode = [NSArray arrayWithObjects:@"20100601", @"20100602", @"20100603", @"20100604", @"20100605", @"20100606", @"20100607", nil];
	// NSArray *typeCode = [NSArray arrayWithObjects:@"N", @"", nil];
	
	NSLog(@"%@", typeCode);

	
	for(int i=0; i<[dateCode count]; i++){
		NSString *dt = [dateCode objectAtIndex:i];
		for(int j=0; j<[typeCode count]; j++){
			NSString *tp = [typeCode objectAtIndex:j];
			
			for(number = 1; number < 9999; number++){

			    NSAutoreleasePool * loopPool = [[NSAutoreleasePool alloc] init];
				
				NSString *trainCode = [NSString stringWithFormat:@"%@%d", tp, number];
				NSLog(@"\n---%@---\n", trainCode);
				fetch_train_stops(trainCode, dt);
				
				[loopPool release];
				
			}
			
		}
	}
	
	
	NSLog(@"done");
	
    [pool drain];
    return 0;
}
